import { NextRequest, NextResponse } from 'next/server'
import { readFile, stat } from 'fs/promises'
import { join } from 'path'

export async function GET(
  request: NextRequest,
  { params }: { params: { toolId: string } }
) {
  try {
    const { toolId } = params
    
    // 构建index.html文件路径
    const filePath = join(process.cwd(), 'public', 'deployed-tools', toolId, 'index.html')
    
    console.log(`访问工具: ${toolId}, 文件路径: ${filePath}`)
    
    // 检查文件是否存在
    try {
      await stat(filePath)
    } catch (error) {
      console.log(`工具文件不存在: ${filePath}`)
      return new NextResponse('Tool not found', { status: 404 })
    }
    
    // 读取HTML文件内容
    const htmlContent = await readFile(filePath, 'utf-8')
    
    console.log(`成功读取工具文件: ${toolId}`)
    
    // 返回HTML内容
    return new NextResponse(htmlContent, {
      status: 200,
      headers: {
        'Content-Type': 'text/html; charset=utf-8',
        'Cache-Control': 'public, max-age=3600', // 缓存1小时
      },
    })
    
  } catch (error) {
    console.error('访问工具失败:', error)
    return new NextResponse('Internal Server Error', { status: 500 })
  }
}
